package com.sunxboy.platform.log4j;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Appender;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

/**
 * This class allows to return preinstantiated appender to log4j E.g. usefull if configuring through config file, where
 * one does not have control over how appenders are created This class is split into two
 */
public class SpringAppenderConfig {

    // @formatter:off
    private static final ThreadLocal<Map<String, Appender>> appenderMap = new ThreadLocal<Map<String, Appender>>() {
        @Override
        protected Map<String, Appender> initialValue() {
            return new HashMap<String, Appender>();
        }
    };

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        /*
         * Everything is done in the constructor;
         */
    }

    /**
     * This is for spring
     * 
     * @param name = appender name to register under
     * @param delegate = actual appender to return for given name
     */
    public SpringAppenderConfig(String name, Appender delegate) {
        appenderMap.get().put(name, delegate);
    }

    public SpringAppenderConfig(Map<String, Appender> appendersMap) {
        appenderMap.get().putAll(appendersMap);
    }

    public static Appender getAppender(String name) {
        return appenderMap.get().get(name);
    }
}
